package com.qf.myscan;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


public class MainActivity extends AppCompatActivity {

    private TextView tv_resultTextView;
    private Button btn_scan;
    private String scanResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        btn_scan.setOnClickListener(view -> scan());
        tv_resultTextView.setOnClickListener(view ->
        {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            cm.setPrimaryClip(ClipData.newPlainText("二维码内容", tv_resultTextView.getText()));
            Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show();
        });

    }

    private void initView() {
        tv_resultTextView = findViewById(R.id.tv_resultTextView);
        btn_scan = findViewById(R.id.btn_scan);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                // 获取扫描结果
                IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
                if (result != null) {
                    // 处理扫描结果
                    if (result.getContents() != null) {
                        scanResult = result.getContents();
                        tv_resultTextView.setText(scanResult);
                        Toast.makeText(this, "点击文本可复制", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }

    }


    private void scan() {
        // 创建 IntentIntegrator 对象
        IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
        // 设置扫描的提示音和震动
        integrator.setBeepEnabled(true);
        integrator.setRequestCode(1);
        integrator.setPrompt("Scan QR Code");
        integrator.setOrientationLocked(true);
        // 开始扫描
        integrator.initiateScan();
    }
}